package com.share.starter.oss.config;

import com.aliyun.oss.OSSClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

/**
 * @author syq
 * @data 2019/7/4
 */

@Slf4j
@Component
public class OssUpload {

   private OssConfig ossConfig = new OssConfig();

    /*这里分隔符 固定为linux分隔符*/
    public String getFullPath(String  fileName){
        return   ossConfig.getBasePath()+"/" + fileName;
    }
    public OSSClient getOssClient(){
        log.info("endpoint="+ossConfig.getEndpoint()+",accessKeyId="+ossConfig.getAccessKeyId()+",accessKeySecret="+ossConfig.getAccessKeySecret());
        return  new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
    }

    public String uploadFile(String fileName,InputStream is){
        String fullPath = getFullPath(fileName);
        OSSClient ossClient = getOssClient();
        ossClient.putObject(ossConfig.getBucketName(),fullPath, is);
        ossClient.shutdown();
        return fullPath;
    }

    public String uploadFile(String fileName,File file){
        String fullPath = getFullPath(fileName);
        OSSClient ossClient = getOssClient();
        ossClient.putObject(ossConfig.getBucketName(),fullPath,file);
        ossClient.shutdown();
        return fullPath;
    }

    /*普通字符串存入oss*/
    public String uploadFile(String fileName,String content)  {
        ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes());
        return uploadFile(fileName,bis);
    }

}
